package ro.savatech.pg.flightlog;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;

public class FlightMem {

	public static final int RECORD_SIZE = 0xfb01;
	private Flight[] flights;

	public static FlightMem fromRaw(FlightIndexEntry[] flightsIndex,
			byte[] rawBytes) {

		FlightMem flightMem = new FlightMem();
		flightMem.flights = new Flight[flightsIndex.length];

		int i = 0;
		for (FlightIndexEntry entry : flightsIndex) {
			byte[] aRawFlight = Arrays.copyOfRange(rawBytes,
					entry.getAddrStart(), entry.getAddrEnd() + 1);
			Flight aFlight = Flight.fromRaw(entry, aRawFlight);
			flightMem.flights[i++] = aFlight;
		}

		return flightMem;
	}

	public Flight[] getFlights() {
		return flights;
	}

	public static FlightMem fromStream(FlightIndexEntry[] flightsIndex, InputStream input) {
		try {
			DataInputStream is = new DataInputStream(input);
			byte[] raw = new byte[FlightMem.RECORD_SIZE];
			is.readFully(raw);

			FlightMem flightMem = FlightMem.fromRaw(flightsIndex, raw);
			return flightMem;
		} catch (IOException e) {
			throw new FLException("Could not read from dump file.", e);
		}
	}
}